<template>
  <div>
    <!-- 查询条件 -->
    <a-row type="flex" justify="space-between" align="middle">
      <div class="flex justify-between">
        <a-input
          class="search-input"
          v-model="userName"
          placeholder="请输入管理员名称"
          allow-clear
        />
        <u-button
          type="primary"
          @click="
            current = 1;
            search();
          "
        >
          查询
        </u-button>
      </div>
      <a-col :span="3" class="flex flex-end">
        <u-button icon="btn-add" @click="add"> 新增管理员 </u-button>
      </a-col>
    </a-row>
    <!-- 表格和分页 -->
    <a-table
      :columns="columns"
      :data-source="data"
      size="small"
      :pagination="false"
      :loading="loading"
      style="margin-top: 10px"
    >
      <span slot="userGender" slot-scope="userGender">
        {{ userGender === 1 ? "男" : "女" }}
      </span>
      <span slot="userStatus" slot-scope="userStatus">
        <div class="text-green" v-if="userStatus === 1">启用</div>
        <div class="text-gray" v-else-if="userStatus === 2">锁定</div>
        <div class="text-gray" v-else-if="userStatus === 3">已锁定</div>
      </span>
      <span slot="action" slot-scope="text">
        <div class="flex">
          <div
            class="mr-10"
            v-if="text.userStatus === 3"
            @click="unlockClick(text)"
          >
            <a-icon class="button-icon" type="unlock" style="color: #1890ff" />
            <span class="button-text">解除锁定</span>
          </div>
          <div
            class="mr-10"
            v-if="text.userStatus === 2 && text.userType != 1"
            @click="enableBtn(text.userId)"
          >
            <a-icon class="button-icon" type="setting" style="color: #1890ff" />
            <span class="button-text">解锁</span>
          </div>
          <div
            class="mr-10"
            v-else-if="text.userStatus === 1 && text.userType != 1"
            @click="disabledBtn(text.userId)"
          >
            <a-icon class="button-icon" type="setting" style="color: #1890ff" />
            <span class="button-text">锁定</span>
          </div>
          <div class="mr-10" @click="edit(text)">
            <a-icon class="button-icon" type="edit" style="color: #1890ff" />
            <span class="button-text">编辑</span>
          </div>
          <div class="mr-10" @click="editPsw(text)">
            <a-icon class="button-icon" type="edit" style="color: #1890ff" />
            <span class="button-text">修改密码</span>
          </div>
          <div class="mr-10" v-if="text.userType != 1" @click="onRemove(text)">
            <a-icon class="button-icon" type="delete" style="color: #1890ff" />
            <span class="button-text">删除</span>
          </div>
        </div>
      </span>
    </a-table>
    <Pagination
      :total="total"
      :defaultPage="page"
      :defaultCurrent="current"
      @sizeChange="
        (val) => {
          page = val;
          current = 1;
          search();
        }
      "
      @currentChange="currentChange"
    />
    <!-- 新增编辑弹窗 -->
    <a-modal
      :maskClosable="false"
      :keyboard="false"
      :title="title"
      :visible="visible"
      :footer="null"
      centered
      :width="600"
      @cancel="visible = false"
    >
      <a-spin tip="Loading..." :spinning="spinning">
        <a-form-model
          ref="ruleForm"
          :model="form"
          :rules="rules"
          labelAlign="left"
          layout="horizontal"
          :label-col="{ span: 5 }"
          :wrapper-col="{ span: 19 }"
        >
          <a-form-model-item
            v-if="!userId"
            label="账号:"
            prop="userAccount"
            style="width: 100%"
          >
            <a-input
              v-model="form.userAccount"
              :max-length="12"
              placeholder="最多输入2到12位的英文字母或英文字母加数字，后期不可修改"
            />
          </a-form-model-item>
          <a-form-model-item
            v-if="!userId"
            label="密码:"
            prop="userPassword"
            style="width: 100%"
          >
            <a-input-password
              v-model="form.userPassword"
              placeholder="请输入密码，应为6-18位字母+数字+特殊符号，不可以有空格"
              @change="pswChange"
            />
          </a-form-model-item>
          <a-form-model-item
            v-if="!userId"
            label="确认密码:"
            prop="confirmPsw"
            style="width: 100%"
            :validate-status="pswStatus"
          >
            <a-input-password
              v-model="form.confirmPsw"
              placeholder="请确认密码，应与之前输入密码相同"
              @change="pswChange"
            />
          </a-form-model-item>
          <a-form-model-item
            label="管理员名称:"
            prop="userName"
            style="width: 100%"
          >
            <a-input
              v-model="form.userName"
              :max-length="12"
              placeholder="请输入2-12个字符"
            />
          </a-form-model-item>
          <a-form-model-item
            label="性别:"
            prop="userGender"
            style="width: 100%"
          >
            <a-select v-model="form.userGender" style="width: 100%">
              <a-select-option
                :value="item.id"
                v-for="(item, index) in sexList"
                :key="index"
              >
                {{ item.name }}
              </a-select-option>
            </a-select>
          </a-form-model-item>
        </a-form-model>
        <div class="flex flex-end mt-10">
          <u-button
            type="default"
            style="font-weight: bold"
            @click="visible = false"
            >取消</u-button
          >
          <u-button class="ml-10 btn-default btn-confirm" @click="confirm">
            确定
          </u-button>
        </div>
      </a-spin>
    </a-modal>
    <!-- 修改密码 -->
    <a-modal
      :maskClosable="false"
      :keyboard="false"
      :title="`修改管理员”${pswInfo.userName}“的密码`"
      :visible="pswVisible"
      :footer="null"
      centered
      :width="600"
      @cancel="pswVisible = false"
    >
      <a-form-model
        ref="pswForm"
        :model="pswForm"
        :rules="pswRules"
        labelAlign="left"
        layout="horizontal"
        :label-col="{ span: 5 }"
        :wrapper-col="{ span: 19 }"
      >
        <a-form-model-item label="新密码:" prop="newPass" style="width: 100%">
          <a-input-password
            v-model="pswForm.newPass"
            placeholder="请输入密码，应为6-18位字母+数字+特殊符号，不可以有空格"
            @change="pswEditChange"
          />
        </a-form-model-item>
        <a-form-model-item
          label="确认密码:"
          prop="confirmPsw"
          style="width: 100%"
          :validate-status="pswStatus"
        >
          <a-input-password
            v-model="pswForm.confirmPsw"
            placeholder="请确认密码，应与之前输入密码相同"
            @change="pswEditChange"
          />
        </a-form-model-item>
      </a-form-model>
      <div class="flex flex-end mt-10">
        <u-button
          type="default"
          style="font-weight: bold"
          @click="pswVisible = false"
          >取消</u-button
        >
        <u-button class="ml-10 btn-default btn-confirm" @click="pswConfirm">
          确定
        </u-button>
      </div>
    </a-modal>
  </div>
</template>
<script>
const columns = [
  // {
  //   title: "序号",
  //   width: 70,
  //   align: "center",
  //   customRender: (text, record, index) => `${index + 1}`,
  // },
  {
    title: "账号",
    dataIndex: "userAccount",
  },
  {
    title: "管理员名称",
    dataIndex: "userName",
  },
  {
    title: "状态",
    key: "userStatus",
    width: "150px",
    dataIndex: "userStatus",
    scopedSlots: { customRender: "userStatus" },
  },

  {
    title: "操作",
    key: "action",
    width: "290px",
    scopedSlots: { customRender: "action" },
  },
];
import Pagination from "@/components/Pagination.vue";
import {
  getSystemUserList,
  disableUser,
  enableUser,
  addSystemUser,
  updateSystemUser,
  resetePassword,
  deleteUser,
  unlockUser,
} from "@/api/user";
import { getSystemRoleList } from "@/api/role";
import { getOrganizationTree } from "@/api/organization";
export default {
  components: {
    Pagination,
  },
  data() {
    return {
      data: [],
      columns,
      loading: false,
      userName: null,
      page: 10,
      current: 1,
      total: 0,
      visible: false,
      title: "新增用户",
      pswStatus: "success",
      userId: null,
      spinning: false,
      form: {
        userAccount: null,
        userPassword: null,
        confirmPsw: null,
        userName: null,
        userGender: 1,
        userRoleId: undefined,
        organizationId: undefined,
        ukeyAuth: 2,
        ukeySn: null,
      },
      rules: {
        userAccount: [
          { required: true, message: "账号不能为空", trigger: "change" },
          { max: 12, message: "最多输入12个字符", trigger: "change" },
          { min: 2, message: "最少输入2个字符", trigger: "change" },
        ],
        userPassword: [
          { required: true, message: "密码不能为空", trigger: "change" },
          // 不能有空格
          {
            pattern: "^[^\\s]*$",
            message: "密码不能包含空格",
          },
          {
            pattern:
              "^(?![0-9]+$)(?![a-zA-Z]+$)(?![0-9a-zA-Z]+$)(?![0-9\\W]+$)(?![a-zA-Z\\W]+$)[0-9A-Za-z\\W]{6,18}$",
            message: "密码必须包含字母、数字和特殊字符，且6-18位之间",
          },
        ],
        userRoleId: [
          { required: true, message: "角色不能为空", trigger: "change" },
        ],
        confirmPsw: [
          { required: true, message: "确认密码不能为空", trigger: "change" },
          {
            pattern: "^[^\\s]*$",
            message: "密码不能包含空格",
          },
        ],
        userName: [
          { required: true, message: "管理员名称不能为空", trigger: "change" },
          { max: 12, message: "最多输入12个字符", trigger: "change" },
          { min: 2, message: "最少输入2个字符", trigger: "change" },
        ],
        organizationId: [
          { required: true, message: "组织不能为空", trigger: "change" },
        ],
      },
      sexList: [
        {
          id: 1,
          name: "男",
        },
        {
          id: 2,
          name: "女",
        },
      ],
      roleList: [],
      treeList: [
        {
          organizationId: 16,
          organizationName: "驾驶行为属性",
          children: [
            {
              organizationId: 137,
              organizationName: "guyufan_test1",
            },
            {
              organizationId: 148,
              organizationName: "温油",
            },
          ],
        },
      ],
      pswInfo: {},
      pswVisible: false,
      pswForm: {
        newPass: "",
        confirmPsw: "",
      },
      pswRules: {
        newPass: [
          { required: true, message: "新密码不能为空", trigger: "change" },
          {
            pattern:
              "^(?![0-9]+$)(?![a-zA-Z]+$)(?![0-9a-zA-Z]+$)(?![0-9\\W]+$)(?![a-zA-Z\\W]+$)[0-9A-Za-z\\W]{6,18}$",

            message: "密码必须包含字母、数字和特殊字符，且6-18位之间",
          },
          {
            pattern: "^[^\\s]*$",
            message: "密码不能包含空格",
          },
        ],
        confirmPsw: [
          { required: true, message: "确认密码不能为空", trigger: "change" },
        ],
      },
      timer: null,
    };
  },
  mounted() {
    this.search();
    this.getRoleList();
    this.getTreeList();
  },
  methods: {
    async search() {
      this.loading = true;
      await this.getList();
      this.loading = false;
    },
    getRoleList() {
      return getSystemRoleList(
        {
          page_index: 1,
          page_size: 0,
        },
        {}
      ).then((res) => {
        this.roleList = res.data.systemRole;
      });
    },
    getTreeList() {
      getOrganizationTree({ paramType: 1 }).then((res) => {
        this.treeList = res.data;
      });
    },
    unlockClick(row) {
      const _this = this;
      this.$confirm({
        title: `提示`,
        content: `确认解锁该管理员吗？`,
        onOk() {
          unlockUser(row.userId).then(() => {
            _this.$message.success("解锁成功");
            _this.search();
          });
        },
        onCancel() {
          _this.$message.info("已取消操作");
        },
      });
    },
    add() {
      this.resetForm();
      this.title = "新增管理员";
      this.visible = true;
      this.userId = null;
      this.form = {
        userAccount: null,
        userPassword: null,
        confirmPsw: null,
        userName: null,
        userGender: 1,
        userRoleId: undefined,
        organizationId: undefined,
        ukeyAuth: 2,
        ukeySn: null,
      };
    },
    edit(text) {
      this.userId = text.userId;
      const {
        userName,
        userGender,
        userRoleId,
        organizationId,
        ukeyAuth,
        ukeySn,
      } = text;

      this.form = {
        userName,
        userGender,
        userRoleId,
        organizationId,
        ukeyAuth,
        ukeySn,
      };
      this.title = "编辑管理员";
      this.visible = true;
    },
    resetForm() {
      this.form = {
        userAccount: null,
        userPassword: null,
        confirmPsw: null,
        userName: null,
        userGender: 1,
        userRoleId: undefined,
        organizationId: undefined,
      };
    },
    // 禁用
    disabledBtn(userId) {
      const _this = this;
      this.$confirm({
        title: `提示`,
        content: `确定锁定该管理员吗？`,
        onOk() {
          disableUser(userId).then(() => {
            _this.$message.success("禁用成功");
            _this.search();
          });
        },
        onCancel() {
          _this.$message.info("已取消操作");
        },
      });
    },
    // 启用
    enableBtn(userId) {
      const _this = this;
      this.$confirm({
        title: `提示`,
        content: `确定启用该管理员吗？`,
        onOk() {
          enableUser(userId).then(() => {
            _this.$message.success("启用成功");
            _this.search();
          });
        },
        onCancel() {
          _this.$message.info("已取消操作");
        },
      });
    },
    confirm() {
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          if (this.userId) {
            const form = JSON.parse(JSON.stringify(this.form));

            delete form.confirmPsw;
            updateSystemUser({ ...form, userId: this.userId }).then(() => {
              this.$message.success("编辑成功");
              this.search();
              this.visible = false;
            });
          } else {
            if (
              this.pswStatus === "error" ||
              this.form.userPassword !== this.form.confirmPsw
            ) {
              this.pswStatus = "error";
              this.$message.error("密码不一致");
              return;
            }
            const form = JSON.parse(JSON.stringify(this.form));
            delete form.confirmPsw;
            addSystemUser(form).then(() => {
              this.$message.success("新增成功");
              this.search();
              this.visible = false;
            });
          }
        } else {
          return false;
        }
      });
    },
    getList() {
      return getSystemUserList(
        {
          page_index: this.current,
          page_size: this.page,
        },
        { userName: this.userName }
      ).then((res) => {
        this.total = res.data.total;
        this.data = res.data.systemUser;
      });
    },
    currentChange(val) {
      this.current = val;
      this.search();
    },
    pswChange(event) {
      clearTimeout(this.timer);
      this.timer = setTimeout(() => {
        if (event.target.value !== this.form.userPassword) {
          this.pswStatus = "error";
        } else {
          this.pswStatus = "success";
        }
      }, 300);
    },
    // 以下为修改密码相关
    editPsw(text) {
      this.pswInfo = text;
      this.pswVisible = true;
      this.$nextTick(() => {
        this.$refs.pswForm.resetFields();
      });
    },
    pswEditChange(event) {
      clearTimeout(this.timer);
      this.timer = setTimeout(() => {
        if (event.target.value !== this.pswForm.newPass) {
          console.log(event.target.value, this.pswForm.newPass, "xaweqarewaq");
          this.pswStatus = "error";
        } else {
          this.pswStatus = "success";
        }
      }, 300);
    },
    pswConfirm() {
      this.$refs.pswForm.validate((valid) => {
        if (valid) {
          if (
            this.pswStatus === "error" ||
            this.pswForm.newPass !== this.pswForm.confirmPsw
          ) {
            this.pswStatus = "error";
            this.$message.error("密码不一致");
            return;
          }
          resetePassword({
            newPass: this.pswForm.newPass,
            userId: this.pswInfo.userId,
          }).then(() => {
            this.$message.success("密码修改成功");
            this.pswVisible = false;
          });
        } else {
          return false;
        }
      });
    },
    // 删除
    onRemove(text) {
      const _this = this;
      this.$confirm({
        title: `提示`,
        content: `此操作将永久删除该数据，是否继续？`,
        onOk() {
          deleteUser(text.userId).then(() => {
            _this.$message.success("已删除");
            _this.current = 1;
            _this.search();
          });
        },
        onCancel() {
          _this.$message.info("已取消删除");
        },
      });
    },
    handleSwitchChange(event) {
      this.form.ukeyAuth = event ? 1 : 2;
    },
  },
};
</script>
<style lang="scss" scoped></style>
